#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "StdThread.h"

//定义一个锁,静态初始化
pthread_mutex_t mutex;//= PTHREAD_MUTEX_INITIALIZER;
int money = 1000;
//zhangsan
void* thread1(void *arg)
{
    pthread_mutex_lock(&mutex);
    printf("张三看到当前余额是：%d\n",money);
    sleep(1);
    int mymoney = money;
    printf("张三准备取钱!\n");
    sleep(1);
    if(mymoney >= 1000)
    {
        money = 0;
        printf("张三拿走了1000！\n");
    }
    else
    {
        printf("余额为0，取钱失败！\n");
    }
    pthread_mutex_unlock(&mutex);
}
//lisi
void* thread2(void *arg)
{
    pthread_mutex_lock(&mutex);
    printf("李四看到当前余额是：%d\n",money);
    sleep(1);
    int mymoney = money;
    printf("李四准备取钱!\n");
    sleep(1);
    if(mymoney >= 1000)
    {
        money = 0;
        printf("李四拿走了1000！\n");
    }
    else
    {
        printf("余额为0，取钱失败！\n");
    }
    pthread_mutex_unlock(&mutex);
}

int main()
{
    //动态初始化锁
    pthread_mutex_init(&mutex,NULL);
    Thread* t1 = InitThread(thread1,NULL);
    Thread* t2 = InitThread(thread2,NULL); 

    ThreadJoin(t1);
    ThreadJoin(t2);

    ClearThread(t1);
    ClearThread(t2);
    //销毁锁
    pthread_mutex_destroy(&mutex);
    return 0;
}